package com.weibo.controller;


import cn.hutool.core.util.IdUtil;
import com.weibo.entity.User;
import com.weibo.resp.UserLoginResp;
import com.weibo.service.UserService;
import com.weibo.utils.ResponseResult;
import com.weibo.utils.enums.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Locale;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    public ResponseResult login(String username, String password){
        User user = userService.getUserByUsernameAndPassword(username, password);

        if(user != null){
            UserLoginResp userLoginResp = new UserLoginResp();
            BeanUtils.copyProperties(user,userLoginResp);
            String token = IdUtil.simpleUUID().toUpperCase(Locale.ROOT);
            log.info("生成token:{}",token);
            userLoginResp.setToken(token);
            //把token作为key,user作为val存入redis
            redisTemplate.opsForValue().set(token,user,30, TimeUnit.MINUTES);

            return new ResponseResult(userLoginResp);
        }else{
            return new ResponseResult(ResultCodeEnum.LOGIN_ERROR);
        }
    }


    @GetMapping("/logout")
    public ResponseResult logout(String token){
        redisTemplate.delete(token);
        return new ResponseResult();
    }
}
